package discuss

import (
	"bytes"
	"encoding/json"
	"errors"
	"go-admin-official/modules/config"
	"io"
	"io/ioutil"
	"net/http"
)

const (
	URIRegisterUser = "http://discuss.go-admin.com/users"
)

type RegisterParam struct {
	Name     string `json:"name"`
	Email    string `json:"email"`
	Password string `json:"password"`
	Username string `json:"username"`
	Active   bool   `json:"active"`
	Approved bool   `json:"approved"`
}

func RegisterUser(p RegisterParam) error {
	b, err := json.Marshal(p)
	if err != nil {
		return err
	}
	res, err := Request("POST", URIRegisterUser, bytes.NewBuffer(b))
	if err != nil {
		return err
	}
	if !res.Success {
		return errors.New(res.Message)
	}
	return nil
}

func Request(method, url string, payload io.Reader) (Response, error) {

	req, err := http.NewRequest(method, url, payload)

	if err != nil {
		return Response{}, err
	}

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Api-Key", config.Get().DiscussSecret)
	req.Header.Add("Api-Username", "system")

	res, err := http.DefaultClient.Do(req)

	if err != nil {
		return Response{}, err
	}

	defer func() {
		_ = res.Body.Close()
	}()
	body, err := ioutil.ReadAll(res.Body)

	if err != nil {
		return Response{}, err
	}

	var data Response
	err = json.Unmarshal(body, &data)

	return data, err

}

type Response struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
}
